package cn.com.kh;

import com.elite.groovy.kh.KHUtil;
import com.elite.groovy.util.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class apiFileProxy extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Log log = LogFactory.getLog(apiFileProxy.class);
    public static EliteBean eliteBean;

    private static final String classString = "apiFileProxy";

    public void destroy() {
        super.destroy();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String fileurl = KHUtil.FastJsonNull(request.getParameter("fileurl"));
        String type = KHUtil.FastJsonNull(request.getParameter("type"));
        log.debug("原始Get请求参数fileurl:" + fileurl + " type:" + type);

        String fileName = fileurl.trim();
        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

        if (KHUtil.isNull(fileName)) {
            fileName = KHUtil.getRandomString(6);
        }

        if (fileurl == null || "".equals(fileurl.trim())) {
            log.warn("FILEURL为空时不处理：" + fileurl);
            return; // FILEURL为空时不处理
        }

        try {
            // 获取token

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse fileresponse = null;
            log.debug("要转发的文件地址：" + fileurl);
            try {
                fileresponse = httpClient.execute(new HttpGet(fileurl));
                HttpEntity entity = fileresponse.getEntity();
                int status = fileresponse.getStatusLine().getStatusCode();
                response.setStatus(status);
                if (status == 200 && entity != null) {

                    Header[] headers = fileresponse.getAllHeaders();
                    boolean isCType = false;
                    for (Header header : headers) {
                        log.debug(header.getName() + ":" + header.getValue());
                        if (header.getName().equals("Content-Type") || header.getName().equals("Content-Length") || header.getName().equals("Access-Control-Allow-Origin") || header.getName().equals("Accept-Ranges")) {
                            if (header.getName().equals("Content-Type") && type.equals("download2")) {
                                log.debug(header.getName() + "###" + header.getValue());
                                response.setHeader("Content-Type", "application/octet-stream;charset=utf-8");
                            } else {
                                response.setHeader(header.getName(), header.getValue());
                            }
                            isCType = true;
                        }

                    }

                    //Content-Type根据文件实际类型设置
                    if (!isCType) {
                        response.setHeader("Content-Type", "application/octet-stream;charset=utf-8");
                        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                    }
                    response.setHeader("Content-Length", entity.getContentLength() + "");
                    response.setHeader("Content-Encoding", "UTF-8");

                    if ((type.equals("download") && isCType) || type.equals("download2")) {
                        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                    }

                    InputStream is = entity.getContent();
                    OutputStream os = response.getOutputStream();

                    byte[] buffer = new byte[1024];
                    int ch;
                    while ((ch = is.read(buffer)) != -1) {
                        os.write(buffer, 0, ch);
                    }
                    is.close();
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (fileresponse != null) {
                        fileresponse.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        } catch (Exception e) {
            log.error("接口处理异常", e);

        }
    }

    public void init() throws ServletException {

        log.info("接口服务" + classString + " 开始初始化...");
        eliteBean = getEliteBean();

        log.info("接口服务" + classString + " 初始化完成...");
    }

    private EliteBean getEliteBean() {
        try {
            ServletContext application = getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(application);
            return (EliteBean) wac.getBean("ebean");
        } catch (Exception e) {
            log.error("接口初始化获取EliteBean失败!");
        }
        return null;
    }

}